package temaihui.daimaitemai;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import temaihui.daimaitemai.adapter.HomeCategoryGridAdapter;
import temaihui.daimaitemai.adapter.HomeGridAdapter;
import temaihui.daimaitemai.adapter.HomeRecommendGridAdapter;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private SlideShowView bannerView;
    private GridView gridView;
    private GridView catgegoryListGrid;
    private GridView recommendGrid;
    private List<HashMap<String,String>> data;
    private HomeDataModel dataModel;
    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        bannerView =(SlideShowView) view.findViewById(R.id.home_banner);
        gridView = (GridView)view.findViewById(R.id.home_grid);
        recommendGrid = (GridView) view.findViewById(R.id.home_recommend_grid);
        catgegoryListGrid = (GridView)view.findViewById(R.id.home_category_grid);

        getData();
        return view;
    }

    private void getData() {
        JSONObject data = new JSONObject();
        try {
            data.put("userId","");
        } catch (Exception e) {

        }
        RequestAction.sendRequest(getActivity(), "appserver/getHomePage", data, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                renderViewByResponse(jsonObject);
                //Log.e("response", jsonObject.toString());

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }
    private void renderViewByResponse(JSONObject jsonObject){

        try {
            dataModel = JSONHelper.parseObject(jsonObject, HomeDataModel.class);
            String[] imageUrls = new String[dataModel.getData().getAdvertList().length];

            for (int i =0; i< dataModel.getData().getAdvertList().length;i++ ) {
                AdModel adModel = dataModel.getData().getAdvertList()[i];
                imageUrls[i]= adModel.getLink();

            }
            bannerView.beginWork(true, imageUrls, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = bannerView.currentItem;
                    Intent intent = new Intent(getContext(), CategoryActivity.class);
                    intent.putExtra("categoryId", dataModel.getData().getAdvertList()[position].getId());
                    intent.putExtra("source", 0);
                    startActivity(intent);

                }
            });
            HomeGridAdapter adapter = new HomeGridAdapter(getActivity(),dataModel.getData().getCategoryGoodsList());
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int itemId = dataModel.getData().getCategoryGoodsList().get(position).getId();
                    Intent intent = new Intent(getContext(), GoodDetailActivity.class);
                    intent.putExtra("itemId", itemId);
                    startActivity(intent);

                }
            });

            HomeRecommendGridAdapter recommendGridAdapter = new HomeRecommendGridAdapter(getActivity(),dataModel.getData().getTagList());
            recommendGrid.setAdapter(recommendGridAdapter);
            recommendGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(getContext(), CategoryActivity.class);
                    intent.putExtra("categoryId", dataModel.getData().getTagList().get(position).getId());
                    intent.putExtra("source", 1);
                    startActivity(intent);
                }
            });
            HomeCategoryGridAdapter categoryGridAdapter = new HomeCategoryGridAdapter(getActivity(),dataModel.getData().getCategoryList());
            catgegoryListGrid.setAdapter(categoryGridAdapter);
            catgegoryListGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    HomeCategoryModel model = dataModel.getData().getCategoryList().get(position);
                    refreshCategoryList(model.getId());

                }
            });

        }catch (Exception e){

        }

    }
    private void refreshCategoryList(int id){
        final JSONObject data = new JSONObject();
        try {
            data.put("userId","");
            data.put("categoryId",id);
        } catch (Exception e) {

        }
        RequestAction.sendRequest(getActivity(), "appserver/getGoodsList", data, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.e("response", jsonObject.toString());
                try {
                    final CategoryListResponseModel dataModel = JSONHelper.parseObject(jsonObject, CategoryListResponseModel.class);
                    HomeGridAdapter adapter = new HomeGridAdapter(getActivity(),dataModel.getData().getList());
                    gridView.setAdapter(adapter);
                    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            int itemId = dataModel.getData().getList().get(position).getId();
                            Intent intent = new Intent(getContext(), GoodDetailActivity.class);
                            intent.putExtra("itemId", itemId);
                            startActivity(intent);
                        }
                    });

                }catch (Exception e){

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }
}
